package com.zxl.register.client;



import com.google.gson.Gson;
import com.zxl.register.base.Event;
import com.zxl.register.base.ServiceInstance;
import com.zxl.register.server.socket.SocketManager;
import lombok.Data;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.*;

@Data
public class Client {



    private static final String server_ip="localhost";

    private static final int server_port=6666;

    private static Random random=new Random();

    private static Gson gson=new Gson();

    private  AsynchronousSocketChannel clientSocketChannel;

    private  String clientName;




    public  void start() throws IOException, ExecutionException, InterruptedException {
        String[] serviceNames={"p1","p2","p3"};
        clientSocketChannel=AsynchronousSocketChannel.open();
        clientSocketChannel.connect(new InetSocketAddress(server_ip, server_port), null, new CompletionHandler<Void, Object>() {

            @Override
            public void completed(Void result, Object attachment) {
                System.out.println("---------  client Started !  ---------  ");
                // 注入到服务中心
                Event event=Event.builder().type("register")
                        .instance(
                                ServiceInstance.builder()
                                        .provideServiceName(serviceNames[random.nextInt(3)])
                                        .subscribeServiceName(serviceNames[random.nextInt(3)])
                                        .build())
                        .build();
                write(gson.toJson(event));
            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });


//        in();

    }

    public  void write(String line){
        ByteBuffer buffer = ByteBuffer.allocate(line.length());
        buffer.put(line.getBytes(StandardCharsets.UTF_8));
        buffer.flip();
        clientSocketChannel.write(buffer, null, new CompletionHandler<Integer, Client>() {
            @Override
            public void completed(Integer result, Client attachment) {
                System.out.println("send finish !!! ");

                try {
                    clientSocketChannel.close();
                    System.out.println(" closed --------- ! ");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void failed(Throwable exc, Client attachment) {
                try {
                    clientSocketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public  void close() throws IOException {
        if(clientSocketChannel!=null){
            clientSocketChannel.close();
        }

    }


    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        int count=1;
//        CountDownLatch latch=new CountDownLatch(count);
        ExecutorService executorService = Executors.newFixedThreadPool(count);
        for(int i=0;i<count;i++){
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 如果latch不会0，则阻塞线程;
                        Client client=new Client();
//                        latch.await();
                        client.start();
                        // 让子线程wait,防止未收到server端的回复就关闭了线程.
//                        Thread.currentThread().wait();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            });
//            latch.countDown();
        }
        // 阻塞主线程，防止主线程结束了。
        Thread.currentThread().wait();
    }



    /**
     * 读取键盘输入字符，传递到server端。可用作调试
     * @throws IOException
     */
    public  void in() throws IOException {
        System.out.println("please enter your command : ");
        try {
            Scanner scanner=new Scanner(System.in);
            ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
            SocketManager.read(clientSocketChannel,null);
            while(true){
                if(scanner.hasNext()){
                    String line =scanner.nextLine();
                    write(line);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close();
        }
    }

}
